﻿using System;
using System.IO;
using System.Net;
using Taobao.ObjectModel;

namespace Jlvier.TaobaoShowcase.Service
{
    public class SessionKey
    {
        private const string SessionKeyValidationURL = "http://container.open.taobao.com/container?authcode={0}";

        private static SessionKey instance;
        private readonly string sessionKey;

        private SessionKey(string sessionKey)
        {
            this.sessionKey = sessionKey;
        }

        public string Value
        {
            get { return sessionKey;}
        }

        public static SessionKey Instance
        {
            get { return instance; }
        }

        public static SessionKey Create(string authenticode)
        {
            try
            {
                WebRequest request = WebRequest.Create(string.Format(SessionKeyValidationURL,authenticode));
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                if (response.StatusCode != HttpStatusCode.OK) throw new SessionKeyException("Error");
                Stream stream = response.GetResponseStream();
                StreamReader reader = new StreamReader(stream);
                string responseFromServer = reader.ReadToEnd();
                string[] parameters = responseFromServer.Split('&');

                foreach (string parameter in parameters)
                {
                    if (parameter.Contains("top_session"))
                    {
                        string sessionKey = parameter.Substring(parameter.IndexOf("=") + 1);
                        instance = new SessionKey(sessionKey);
                        return instance;
                    }
                }
                reader.Close();
                stream.Close();
                response.Close();
            }
            catch (WebException e)
            {
                throw new SessionKeyException(e.Message,e);
            }
            catch (Exception e)
            {
                throw new SessionKeyException(e.Message,e);
            }
            throw new SessionKeyException(SR.AuthenticcodeTimeOut);
        }

    }
}